package com.zjgsu.demo.controller;

import com.zjgsu.demo.Repository.DeviceRepository;
import com.zjgsu.demo.Repository.TroubleRepository;
import com.zjgsu.demo.nodeEntity.Trouble;
import com.zjgsu.demo.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/rest/v1.0/database/trouble")
public class TroubleController {
    @Autowired
    TroubleRepository troubleRepository;
    DeviceRepository deviceRepository;


    @GetMapping("/get")
    public Trouble findTroubleByName(@RequestParam(value = "name") String name){

        Trouble trouble = troubleRepository.findTroubleByName(name);

        return trouble;
    }
    //存储实体
    @PostMapping("/save")
    public ResponseResult createTrouble(@RequestBody Trouble trouble) throws Exception{

        Trouble result = troubleRepository.save(trouble);
        if(result!=null){
            return new ResponseResult(200,result.getName()+"节点创建成功！");
        }
        return new ResponseResult(500, trouble.getName()+"节点创建失败！");
    }
    //获取全部实体
    @PostMapping("/all")
    public Iterable<Trouble> all() throws Exception{
        Iterable<Trouble> troubles = troubleRepository.findAll();
        return troubles;
    }

    //添加隐患里的设备
    @GetMapping("/addDevice")
    public ResponseResult troubleAddDevice(@RequestParam(value="troubleName") String troubleName,@RequestParam(value="deviceTitle") String deviceTitle) throws Exception{
        troubleRepository.troubleAddDevice(troubleName,deviceTitle);
        if(troubleRepository.findTroubleByName(troubleName) == null && deviceRepository.findDeviceByTitle(deviceTitle) == null){
            return new ResponseResult(200, troubleName+"加入"+deviceTitle+"失败");
        }
        return new ResponseResult(200, troubleName+"加入"+deviceTitle+"成功");
    }

    //添加设备的隐患

    @GetMapping("/addTrouble")
    public ResponseResult deviceAddtrouble(@RequestParam(value="troubleName") String troubleName,@RequestParam(value="deviceTitle") String deviceTitle) throws Exception{
        troubleRepository.deviceAddTrouble(troubleName,deviceTitle);
        if(troubleRepository.findTroubleByName(troubleName) == null && deviceRepository.findDeviceByTitle(deviceTitle) == null){
            return new ResponseResult(200, deviceTitle+"加入"+troubleName+"失败");
        }
        return new ResponseResult(200, deviceTitle+"加入"+troubleName+"成功");
    }
    //删除隐患里的设备
    @GetMapping("/deleteDevice")
    public void troubleDelDevice(@RequestParam(value="troubleName") String troublename,@RequestParam(value="deviceTitle") String deviceTitle) throws Exception{
        troubleRepository.troubleDeleteDevice(troublename,deviceTitle);
    }
}
